<template>
  <van-nav-bar :title="query.pickNo" left-arrow @click-left="onClickLeft" placeholder fixed />
  <van-list v-if="showSn == 1" v-model:loading="loading" :finished="finished" :loading-text="t('loading')" @load="onLoad" >
    <div v-for="(list, i) in pickSkuGroupList" :key="i">
      <van-row class="font-bold py-2 px-4 van-hairline--surround">
        <span style="font-size: 1.2rem">{{ list[0].regionCode }}#</span>
      </van-row>
      <van-cell center v-for="(item, i) in list" :key="i" @click="showDetail(item)">
        <template #title>
          {{ t('pick.locationCode') }}{{ item.locationCode }}<br>SKU：{{ item.skuCode }}
        </template>
        <template #right-icon>
          {{ item.realPickNum + '/' + item.pickNum }}
        </template>
      </van-cell>
    </div>
  </van-list>
  <div v-if="showSn == 2">
    <van-cell center class="p-2">
      <template #title>
        <span class="font-bold">{{ t('pick.locationCode') }}{{ currentPickSku.locationVoList[currentLocationIndex].locationCode }}</span>
        <br>
        <span>SKU：{{ currentPickSku.skuCode }}</span>
      </template>
      <template #right-icon>
        <div class="w-2/5">
          <van-button class="float-right" type="primary" @click="markLack">{{ t('pick.markLack') }}</van-button>
        </div>
      </template>
    </van-cell>
<!--    <van-field ref="locationRef" v-model="locationValue" size="large" @keydown.enter="handleScanLocation" :placeholder="t('pick.pleaseScanningLocation')" clearable>-->
<!--      <template #left-icon>-->
<!--        <van-icon name="enlarge" size="1.5rem" class="px-2"/>-->
<!--      </template>-->
<!--    </van-field>-->
    <van-field ref="skuRef" v-model="skuValue" size="large" @keydown.enter="handleScanSku" :placeholder="t('pick.pleaseScanningSku')" clearable>
      <template #left-icon>
        <van-icon name="enlarge" size="1.5rem" class="px-2"/>
      </template>
    </van-field>
    <van-cell-group class="mt-1 text-center p-2">
      <van-row>
        <van-col span="12">{{ t('pick.toPickCount') }}</van-col>
        <van-col span="12">{{ t('pick.pickedCount') }}</van-col>
      </van-row>
      <van-row class="mt-1 font-bold">
        <van-col span="12">
          <van-field center readonly input-align="center" :model-value="currentPickSku.pickNum" style="font-size: xx-large" />
        </van-col>
        <van-col span="6" offset="3">
          <van-field center input-align="center" :max="parseInt(currentPickSku.pickNum)" type="digit" @keydown.enter="handleSkuNum" v-model="currentPickSku.realPickNum" class="input-border">
          </van-field>
        </van-col>
      </van-row>
    </van-cell-group>
    <van-cell-group class="text-center" :title="t('pick.relatedLocation')">
      <van-row class="font-bold py-2 van-hairline--surround ">
        <van-col class="van-hairline--right" span="8">{{ t('pick.region') }}</van-col>
        <van-col class="van-hairline--right" span="8">{{ t('pick.location') }}</van-col>
        <van-col span="8">{{ t('pick.pickType') }}</van-col>
      </van-row>
      <template v-for="(item, i) in currentPickSku.locationVoList" :key="i">
        <van-row :class="currentLocationIndex == i ? 'py-2 van-hairline--surround bg-blue-200' : 'py-2 van-hairline--surround'">
          <van-col class="van-hairline--right" span="8">{{ item.regionCode }}</van-col>
          <van-col class="van-hairline--right" span="8">{{ item.locationCode }}</van-col>
          <van-col span="8">{{ item.pickType == 0 ? t('enums.pickType.pickUp') : item.pickType == 1 ? t('enums.pickType.storageSpaces') : item.pickType}}</van-col>
        </van-row>
      </template>
    </van-cell-group>
    <van-action-bar placeholder>
      <van-row gutter="10" class="w-full p-1">
        <van-col span="12">
          <van-button class="text-base" block plain @click="continuePick">{{ t('pick.continuePick') }}</van-button>
        </van-col>
        <van-col span="12">
          <van-button class="text-base" block type="primary" @click="endPick">{{ t('pick.endPick') }}</van-button>
        </van-col>
      </van-row>
    </van-action-bar>
  </div>
  <div v-if="showSn == 3">
    <van-cell-group class="text-center text-r">
      <van-row class="font-bold py-3 van-hairline--surround ">
        <van-col class="van-hairline--right" span="12">SKU</van-col>
        <van-col span="12">{{ t('pick.pickedInfo') }}</van-col>
      </van-row>
      <van-row v-for="(item, i) in pickSkuList" :key="i" class="py-3 van-hairline--surround" @click="showDetail(item)">
        <van-col class="van-hairline--right" span="12">{{ item.skuCode }}</van-col>
        <van-col span="12">
          <span class="text-red-600" v-if="item.realPickNum != item.pickNum">{{ item.realPickNum }}</span>
          <span v-else>{{ item.realPickNum }}</span>
          /
          {{ item.pickNum }}
        </van-col>
      </van-row>
    </van-cell-group>
    <van-action-bar placeholder>
      <van-row gutter="10" class="w-full p-1">
        <van-col span="24">
          <van-button class="text-base" block :loading="confirmLoading" type="primary" @click="confirmPick">{{ t('pick.endPick') }}</van-button>
        </van-col>
      </van-row>
    </van-action-bar>
  </div>
  <van-back-top />
</template>

<script setup lang="ts">
import { useI18n } from "vue-i18n";
import { postRequest, scanSuccess, scanFail, getRequest } from "@/api";
import { useRoute } from "vue-router";
import { showFailToast, showDialog, showConfirmDialog } from "vant";
import { AppToast } from "@/utils/appToast";

const query: any = useRoute().query;
const { t } = useI18n();
const onClickLeft = () => {
  showSn.value -= 1
  if(!showSn.value) {
    history.back();
  }
}

const finished = ref(false);
const loading = ref(false);
const confirmLoading = ref(false);
const skuReadonly = ref(true);
// const locationRef = ref();
const locationValue = ref();
const skuRef = ref();
const skuValue = ref();

const showSn = ref(1);

const pickSkuList = ref([]);
const pickSkuGroupList = ref([]);

const currentPickSku : any = ref({});
const currentPickSkuIndex = ref(null);
const currentLocationIndex = ref(0);

const onLoad = () => {
  getRequest("/pick/sku/list/" + query.pickId, {}).then(res => {
    pickSkuList.value = res.data;
    res.data.forEach((item) => {
      const arr = pickSkuGroupList.value[pickSkuGroupList.value.length -1] ?? [];
      if (arr[arr.length-1]?.regionCode == item.regionCode) {
        arr.push(item)
      } else {
        pickSkuGroupList.value.push([item])
      }
    });
    loading.value = false;
    finished.value = true;
  }).catch(() => {
    loading.value = false;
    finished.value = true;
  })
};

const showDetail = (pickSku) => {
  showSn.value = 2;
  currentPickSku.value = pickSku;
  currentPickSkuIndex.value = pickSkuList.value.indexOf(pickSku)
  currentLocationIndex.value = 0;
  skuReadonly.value = true;
  locationValue.value = null;
  skuValue.value = null;
  nextTick(() => skuRef.value.focus())
}

// const handleScanLocation = () => {
//   if (locationValue.value) {
//     if (locationValue.value == currentPickSku.value.locationVoList[currentLocationIndex.value].locationCode) {
//       scanSuccess();
//       skuReadonly.value = false;
//       nextTick(() => skuRef.value.focus())
//     } else {
//       locationValue.value = null;
//       showFailToast(t('pick.locationNotMatch'));
//       scanFail();
//     }
//   }
// }

const handleScanSku = () => {
  if (skuValue.value) {
    if (skuValue.value.toLowerCase() === currentPickSku.value.skuCode.toLowerCase()) {
      scanSuccess();
      currentPickSku.value.realPickNum = 1 + parseInt(currentPickSku.value.realPickNum);
      handleSkuNum();
    } else {
      showFailToast(t('pick.skuNotMatch'));
      scanFail();
    }
    skuValue.value = null;
  }
}

const handleSkuNum = () => {
  currentPickSku.value.realPickNum = parseInt(currentPickSku.value.realPickNum);
  if (currentPickSku.value.realPickNum == currentPickSku.value.pickNum) {
    if (nextPickSku(pickSkuList.value.length)) {
      showFailToast(t('pick.nextSku'));
      currentLocationIndex.value = 0;
      skuReadonly.value = true;
      locationValue.value = null;
      nextTick(() => skuRef.value.focus())
    }
  }
}

const nextPickSku = (loopCount) => {
  if (loopCount > 0) {
    currentPickSkuIndex.value += 1;
    if (currentPickSkuIndex.value >= pickSkuList.value.length) {
      currentPickSkuIndex.value = 0;
    }
    const nextSku = pickSkuList.value[currentPickSkuIndex.value];
    if (nextSku.realPickNum == nextSku.pickNum) {
      nextPickSku(--loopCount)
    } else {
      showDetail(nextSku);
      return true;
    }
  } else {
    showDialog({
      message: t('pick.finishConfirm'),
    }).then(() => {
      showSn.value = 3;
    });
    return false;
  }
}

const continuePick = () => {
  if (currentPickSku.value.realPickNum < currentPickSku.value.pickNum) {
    showConfirmDialog({
      message: t('pick.notFinishConfirm'),
      confirmButtonText: t('pick.continue'),
      cancelButtonText: t('pick.end'),
    }).then(() => {
      let newLocationIndex = currentLocationIndex.value + 1;
      if (newLocationIndex >= currentPickSku.value.locationVoList.length) {
        newLocationIndex = 0;
      }
      if (newLocationIndex != currentLocationIndex.value) {
        currentLocationIndex.value = newLocationIndex;
        skuReadonly.value = true;
        locationValue.value = null;
        skuValue.value = null;
        nextTick(() => skuRef.value.focus())
      }
    }).catch(() => {
      nextPickSku(pickSkuList.value.length)
    });
  } else {
    nextPickSku(pickSkuList.value.length)
  }
}

const endPick = () => showSn.value = 3

const confirmPick = () => {
  confirmLoading.value = true
  postRequest("/pick/confirm/" + query.pickId, pickSkuList.value).then(() => {
    AppToast(t("pick.pickedSuccess"), "success")
    history.back();
  }).finally(() => {
    confirmLoading.value = false
  })
}

const markLack = () => {
  postRequest("/stock/markLack/" + currentPickSku.value.skuId, {}).then(() => {
    AppToast(t("pick.markLackSuccess"), "success")
  })
}
</script>

<style scoped lang="less">
:deep(.van-cell) {
  font-size: 1rem;
}

:deep(.van-nav-bar__title) {
  font-size: 1rem;
  font-weight: 500;
  color: white;
}

:deep(.van-nav-bar__content) {
  background: #1b82d2;
}

:deep(.van-nav-bar .van-icon) {
  color: white;
}

:deep(.input-border) {
  border: 1px solid #e5e7eb;
  font-size: xx-large;
}
</style>
